import { observable, computed, action, toJS } from "mobx";
import { isEqual } from 'lodash';
import { listDataSetTableFields } from "../../apis/dataset";
import CellType from './celltypes';
import { WeaLocaleProvider,WeaInputLocale } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const getCurrentLabel = WeaInputLocale.getCurrentLabel;
export default class FieldPropsStore {
    @observable tabs = [
    //     {
    //     key: '0',
    //     title: getLabel('506118','单元格'),
    //     icon: 'icon-coms-classification'
    // }, 
    {
        key: '1',
        title: getLabel('506120','表单设置'),
        icon: 'icon-coms-Flow-setting'
    }, {
        key: '2',
        title: getLabel('506121','显示设置'),
        icon: 'icon-coms-pic',
        disabled: true
    }];
    @observable selectedTabKey = '0';

    @observable dataSetList = [];
    @observable dataSetMap = {};
    @observable range;
    @observable table;

    @observable visible = true;
    @observable rowControl={};
    @observable cellTypeId = "";
    @observable expandType = "0";
    @observable isCustomDetail;
    @observable showExpandType = false;
    oldValue;

    @computed get selectedIndex() {
        let index = 0;
        this.tabs.forEach((t, i) => {
            if (t.key === this.selectedTabKey) {
                index = i;
            }
        });
        return index;
    }
    @computed get tabsLength() {
        return this.tabs.length;
    }

    @computed get content() {
        return this.range && this.range.value();
    }
    cellType() {
        return this.range && ((this.table && this.table.bindingPath()) ? this.range.sheet.getCell(this.table.dataRange().row, this.range.col).cellType() : this.range.cellType());
    }
    cell() {
        return this.range && ((this.table && this.table.bindingPath()) ? this.range.sheet.getCell(this.table.dataRange().row, this.range.col) : this.range);
    }
    @computed get label() {
        const cellType = this.cellType();

        if(cellType) {
            const multilang = cellType.multilang;
            const label = cellType.label;
            this.oldValue = cellType.label;
            const{row, col} = this.range;
            this.relatedCell = undefined;
            // 先判断左边字段
            if(col > 0) {
                const leftCell = this.range.sheet.getCell(row, col-1);
                const leftcellType = leftCell.cellType();
                const leftValue = leftCell.value();
                if(!leftcellType && leftValue && leftValue == this.oldValue) {
                    this.relatedCell = leftCell;
                } else if(row > 0) {
                    const topCell = this.range.sheet.getCell(row-1, col);
                    const topcellType = topCell.cellType();
                    const toptValue = topCell.value();
                    if(!topcellType && toptValue && toptValue == this.oldValue) {
                        this.relatedCell = topCell;
                    }
                }
            }

            return multilang ? multilang : label;
        } else if(this.cell()){
            const value = this.cell().value();
            const tag = this.cell().tag();

            if(value) {
                return (tag && tag.typeof==='string' &&tag.indexOf(value) > -1) ? tag : value;
            }
        }
        
    }
    @computed get columnName() {
        const cellType = this.cellType();
        return cellType && cellType.fieldName;
    }
    @computed get viewAttr() {
        const cellType = this.cellType();
        return cellType && cellType.viewAttr;
    }

    @computed get fieldVisible() {
        const cellType = this.cellType();
        return cellType && cellType.fieldVisible;
    }

    @computed get dbName() {
        const cellType = this.cellType();
        return cellType && cellType.dbName;
    }

    @computed get tableName() {
        const cellType = this.cellType();
        return cellType && (cellType.tableName != '0' ? cellType.tableName : '' );
    }
    getExpandType = () => {
        const cellType = this.cellType();
        return (cellType && cellType.expandType) || "0";
    }
    @computed get fieldType() {
        const cellType = this.cellType();
        return cellType && cellType.fieldType;
    }
    @computed get htmlType() {
        return this.fieldType && this.fieldType[0];
    }
    @computed get type() {
        return this.fieldType && this.fieldType[1];
    }
    @computed get isField() {
        const cellType = this.cellType();
        return !!(cellType && cellType.fieldType);
    }
    @computed get options() {
        const cellType = this.cellType();
        return cellType && cellType[2] && cellType[2].datas;
    }
    @computed get dbType() {
        return this.fieldType && this.fieldType[2];
    }
    @computed get tableOptions() {
        const list = this.dataSetMap[this.dataSet] || [];
        return list.map(({ key, showname }) => ({ key, showname }));
    }
    @computed get tableFieldOptions() {
        const list = this.dataSetMap[this.dataSet] || [];
        const tableArray = list.filter(d => d.key != "" && d.key === this.dsTable);
        let fieldOptions = [];
        if (tableArray.length > 0) {
            if(tableArray[0].children){
                fieldOptions = tableArray[0].children.map(d => ({ key: d.key, showname: d.showname }));
            }
        }
        fieldOptions.unshift({key:"",showname:""});
        return fieldOptions;
    }
    @computed get dataSet() {
        const cellType = this.cellType();
        return cellType && cellType.ds;
    }
    set dataSet(ds) {
        this.updateSheet(() => {
            let cellType = this.cellType();
            if (cellType) {
                cellType.ds = ds;
                this.cellTypeId = cellType.id; 
            } else {
                const NoFieldCellType = CellType('NoFieldCellType');
                cellType = new NoFieldCellType();
                cellType.ds = ds;
                this.range.cellType(cellType);
            }
            cellType.dsName = (this.dataSetList.filter(d => d.key === ds)[0] || {}).showname;
            this.parent().reEnterCell();
        })

    }
    @computed get dsTable() {
        const cellType = this.cellType();
        return cellType && cellType.table;
    }
    set dsTable({ table, tableName }) {
        this.updateSheet(() => {
            let cellType = this.cellType();
            if (cellType) {
                cellType.table = table;
                cellType.tableName = tableName;
                this.cellTypeId = cellType.id; 
            } else {
                const NoFieldCellType = CellType('NoFieldCellType');
                cellType = new NoFieldCellType();
                cellType.table = table;
                cellType.tableName = tableName;
                this.range.cellType(cellType);
            }
            this.parent().reEnterCell();
        })
    }
    @computed get dsField() {
        const cellType = this.cellType();
        return cellType && cellType.field;
    }
    set dsField(field) {
        this.updateSheet(() => {
            let cellType = this.cellType();
            if (cellType) {
                cellType.field = field;
                this.cellTypeId = cellType.id; 
            } else {
                const NoFieldCellType = CellType('NoFieldCellType');
                cellType = new NoFieldCellType();
                cellType.field = field;
                this.range.cellType(cellType);
            }
            this.parent().reEnterCell();
        })
    }

    @action toggle = () => {
        this.visible = !this.visible;
    }
    @action setdataSetList = (dataSetList) => {
        if (!isEqual(toJS(this.dataSetList), toJS(dataSetList))) {
            this.init(dataSetList);
        }
        this.dataSetList = dataSetList;
    }
    @action init = (list) => {

        // Promise.all(list.map(ds => {
        //     if (ds.key != "") {
        //         return listDataSetTableFields(ds.key);
        //     }
        // })).then(result => {
        //     const dataSetMap = {};
        //     list.forEach((ds, index) => {
        //         if(ds.key){
        //             dataSetMap[ds.key] = [{ key: "", showname: "" }].concat(result[index]);
        //         }
        //     });
        //     this.dataSetMap = dataSetMap;
        // });
    }
    @action initProps = (dataSetList, range, table, rowControl) => {
        dataSetList = dataSetList.map(d => ({ key: d.uuid, showname: d.name,disabled: d.disabled }));
        dataSetList.unshift({ key: "", showname: "" });
        this.setdataSetList(dataSetList);
        this.range = range;
        
        this.table = table;
        this.isCustomDetail = table && !table.bindingPath() && table.name().startsWith("custom");
        this.rowControl = rowControl;
        const {row, col} = range;
        const cellType= this.range.sheet.getCell(row, col).cellType();

        if(this.isCustomDetail && cellType) {
            // if(cellType.fieldType) {
            //     const type =  cellType.fieldType[0];
            //     if(type == 'select' || type == 'browser') {
            //         this.showExpandType = true;
            //     } else {
            //         this.showExpandType = false;
            //     }
            // } else {
            //     this.showExpandType = false;
            // }
            this.showExpandType = true;
        } else {
            this.showExpandType = false;
        }
        this.expandType = this.getExpandType();
        if (this.isField) {
            if(this.cellType().id !== this.cellTypeId) {
                this.selectedTabKey = '1';
            } 
        } else {
            //this.selectedTabKey = '0';
            this.selectedTabKey = '1';
        }

    }
    @action changeFieldLabel = (label) => {
        label = label ? label + "" : label;
        if (this.range) {
            this.range.sheet.suspendPaint();
            const cellType = this.cellType();
            if (cellType) {
                let currentLabel = getCurrentLabel(label);
                if(!currentLabel) {
                    currentLabel = getCurrentLabel(label,"7")
                }
                cellType.label = currentLabel;
                cellType.multilang = label;
                if (this.table && this.table.bindingPath()) {
                    const index = this.range.col - this.table.dataRange().col;
                    this.table.setColumnName(index, currentLabel);
                } else {
                    // 主表字段
                    
                    if(this.relatedCell) {
                        this.relatedCell.value(currentLabel);
                        this.relatedCell.tag(label);
                    }
                }
            } else {
                let currentLabel = getCurrentLabel(label);
                if(!currentLabel) {
                    currentLabel = getCurrentLabel(label,"7")
                }
                this.cell().value(currentLabel);
                this.cell().tag(label);
            }
            this.range.sheet.resumePaint();
        }

    }
    @action changeExpandType = (e) => {
        const value = e.target.value;
        // todo 此处还需要验证下是否是自定义明细表字段
        if (this.range) {
            this.range.sheet.suspendPaint();
            const cellType = this.cellType();
            if (cellType) {
                cellType.expandType = e.target.value;
                if(value != "0") {
                    this.cell().textIndent(5);
                } else {
                    this.cell().textIndent(2.5);
                }
                this.expandType = e.target.value;
            }
            this.range.sheet.resumePaint();
        }

    }
    @action changeDataSet = (ds) => {
        this.dataSet = ds;
        this.dsTable = {};
        this.dsField = "";
    }
    @action changeDataSetTable = (table) => {
        const tableName = (this.tableOptions.filter(d => d.key === table)[0] || {}).showname || '';
        this.dsTable = { table, tableName };
        this.dsField = "";
    }
    @action changeDataSetField = (field) => {
        this.dsField = field;
    }

    @action changeViewAttr = (viewAttr) => {
        const cellType = this.cellType();
        if(cellType) {
            cellType.viewAttr = viewAttr;
        }
    }

    @action changeFieldVisible = (visible) => {
        const cellType = this.cellType();
        if(cellType) {
            
            this.range.sheet.suspendPaint();
            cellType.fieldVisible = visible;
            const backgroundImage = this.cellType().getFieldTypeImage();
            this.cell().backgroundImage(backgroundImage);
            this.range.sheet.resumePaint();
        }
    }
    

    updateSheet = (func) => {
        this.range.sheet.suspendPaint();
        func();
        this.range.sheet.resumePaint()
    }

    @computed get isAddRow() {
        let result = 1;
        if (this.table) {
            const bindingPath = this.table.bindingPath();
            if(!bindingPath) {
                return;
            }
            const paths = bindingPath.split('.');
            const sheetName = paths[0];
            if(this.rowControl && this.rowControl[sheetName]){
                this.rowControl[sheetName].forEach(item => {
                    if(bindingPath == item.bindingPath){
                        result = item.isAddRow;
                        return;
                    }
                });
            }
        }  
        return result;
    }

    @computed get isDeleteRow() {
        let result = 1;
        if (this.table) {
            const bindingPath = this.table.bindingPath();
            if(!bindingPath) {
                return;
            }
            const paths = bindingPath.split('.');
            const sheetName = paths[0];
            if(this.rowControl && this.rowControl[sheetName])
            this.rowControl[sheetName].forEach(item => {
                if(bindingPath == item.bindingPath){
                    result = item.isDeleteRow;
                    return;
                }
            });
        }  
        return result;
    }

    @action changeRowControl = (type, isRowControl) => {
        if (this.table) {
            const bindingPath = this.table.bindingPath();
            if(!bindingPath) {
                return;
            }
            const paths = bindingPath.split('.');
            const sheetName = paths[0];
            const rowControl  = this.rowControl;
            if(rowControl){
                if(rowControl[sheetName]){
                    var arr= rowControl[sheetName].filter(function(item){
                        return item.bindingPath == bindingPath; 
                    })
                    if(arr.length==0){
                        if('add' == type){
                            let tableControl= {bindingPath: bindingPath ,isAddRow: isRowControl,isDeleteRow: 1};
                            rowControl[sheetName].push(tableControl);
                        } else if('delete' == type){
                            let tableControl= {bindingPath: bindingPath ,isAddRow: 1, isDeleteRow: isRowControl};
                            rowControl[sheetName].push(tableControl);
                        }
                    } else {
                        rowControl[sheetName].forEach(item => {
                            if(bindingPath == item.bindingPath){
                                if('add' == type){
                                    item.isAddRow = isRowControl;
                                } else if('delete' == type){
                                    item.isDeleteRow = isRowControl;
                                }
                                return;
                            }
                        });
                    }
                } else {
                    let sheetControl = new Array();　
                    if('add' == type){
                        let tableControl= {bindingPath: bindingPath ,isAddRow: isRowControl,isDeleteRow: 1};
                        sheetControl.push(tableControl);
                    } else if('delete' == type){
                        let tableControl= {bindingPath: bindingPath ,isAddRow: 1, isDeleteRow: isRowControl};
                        sheetControl.push(tableControl);
                    }
                    rowControl[sheetName] = sheetControl;
                }
            } else {
                let sheetControl = new Array();　
                if('add' == type){
                    let tableControl= {bindingPath: bindingPath ,isAddRow: isRowControl,isDeleteRow: 1};
                    sheetControl.push(tableControl);
                } else if('delete' == type){
                    let tableControl= {bindingPath: bindingPath ,isAddRow: 1, isDeleteRow: isRowControl};
                    sheetControl.push(tableControl);
                }
                rowControl[sheetName] = sheetControl;
            }
        }
    }

    @computed get imageWidth() { 
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            return cellType.fieldType[2];
        }
    }

    set imageWidth(value) {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            cellType.fieldType[2] = value;
        }
    }

    @computed get imageHeight() {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            return cellType.fieldType[3];
        }
    }

    set imageHeight(value) {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            cellType.fieldType[3] = value;
        }
    }

    @computed get textLength() {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            return cellType.fieldType[2];
        }
    }

    set textLength(value) {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            cellType.fieldType[2] = value;
        }
    }

    @computed get floatLength() {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            return cellType.fieldType[2];
        }
    }

    set floatLength(value) {
        const cellType = this.cellType();
        if((cellType && cellType.fieldType)) {
            cellType.fieldType[2] = value;
        }
    }

    @action changeImageWidth = (value)  => {
        this.imageWidth = value;
     }
 
    @action changeImageHeight = (value)  => {
        this.imageHeight = value;
    }

    @action changeTextLength = (value)  => {
        this.textLength = value;
    }

    @action changeFloatLength = (value)  => {
        this.floatLength = value;
    }

    @computed get hasData() {
        const cellType = this.cellType();
        return cellType && cellType.hasData;
    }

    @computed get parentFieldName() {
        const cellType = this.cellType();
        return cellType && cellType.parentFieldName;
    }

}